<script>
  import { moment } from 'istrong-timeutil'
  import { DatetimePicker } from 'mint-ui';

  export default {
    name: 'dateTimePicker',
    components: {
      'mint-datetimepicker': DatetimePicker
    },
    props: {
      format: {
        type: String,
        default: 'YYYY-MM-DD'
      },
      datetype: {
        type: String,
        default: 'datetime'
      },
      cancelText: {
        type: String,
        default: '取消'
      },
      confirmText: {
        type: String,
        default: '确定'
      },
      value: {
        type: String,
        default: moment().format('YYYY-MM-DD')
      },
      clearEnabled: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        pickerValue: moment().toDate()
      }
    },
    watch: {
      value(val) {
        let time = moment(val);
        this.pickerValue = this.datetype === 'time' ? time.format('HH:mm') : time.toDate();
      }
    },
    mounted() {
      let val = moment(this.value);
      this.pickerValue = this.datetype === 'time' ? val.format('HH:mm') : val.toDate();
    },
    methods: {
      openPicker() {
        this.$refs.picker.open();
      },
      clearPicker() {
        this.$emit('input', '');
        this.pickerValue = moment().toDate();
      },
      handleConfirm(value) {
        this.$emit('input', moment(value).format('YYYY-MM-DDTHH:mm:ss'));
      }
    },
    computed: {
      formatValue: function () {
        return this.value === '' ? '' : moment(this.value).format(this.format);
      }
    }
  }
</script>

<template>
  <div class="dateTimePicker">
    <div class="dateTimeValue" v-on:click="openPicker" :class="clearEnabled ? 'dateTimeValue-ClearEnabled' : ''">{{formatValue}}</div>
    <div class="dateTimePicker-Button">
      <div class="ion-close-circled dateTimePicker-clear" v-on:click="clearPicker" v-if="clearEnabled"></div>
      <div class="ion-chevron-right dateTimePicker-after" v-on:click="openPicker"></div>
    </div>
    <mint-datetimepicker class="mint-datetimepicker" ref="picker" :type="datetype" v-model="pickerValue" :cancelText="cancelText"
      :confirmText="confirmText" @confirm="handleConfirm">
    </mint-datetimepicker>
  </div>
</template>
<style>
.dateTimePicker{
  border: 1px solid #EEEDF1;
  background-color: #fff;
  font-size: 16px;
  color: #666666;
  position: relative;
  height: 25px;
}
.dateTimeValue{
  padding-right: 18px;
  line-height: 25px;
  height: 25px;
  white-space: nowrap;
  display: block;
  text-overflow: ellipsis;
  overflow: hidden;
}
.dateTimeValue-ClearEnabled{
  padding-right: 42px;
}
.dateTimePicker-Button{
  position: absolute;
  right: 0px;
  top: 0px;
  z-index: 2;
}
.dateTimePicker-clear,.dateTimePicker-after{
  float: left;
  width: 15px;
  font-size: 18px;
  line-height: 25px;
  padding: 0px 3px;
  color: #bbb;
}
.dateTimePicker-clear{
  font-size:17px;
}
</style>